from PyQt5 import QtCore, QtGui, QtWidgets, QtWebEngineWidgets
import urllib.request, urllib.error, time
from PyQt5.QtCore import Qt
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from test import QMainWindow_new

class Ui_tensorboradshow(QMainWindow_new):

    def __init__(self):
        super(Ui_tensorboradshow, self).__init__()
        self.setupUi(self)

    def setupUi(self, tensorboradshow):
        label_backdrop = QLabel(self)
        label_backdrop.resize(1460, 800)
        label_backdrop.setStyleSheet("background-color: rgb(240, 250, 250);")

        label_title = QLabel(self)
        label_title.resize(1460, 50)
        label_title.setText("    训练结果查看")
        label_title.setFont(QtGui.QFont("Adobe 黑体 Std R", 18))
        label_title.setStyleSheet("background-color: rgb(50, 200, 200);")

        label_T = QLabel(self)
        label_T.resize(40, 40)
        label_T.move(5, 5)
        label_T.setPixmap(QPixmap(r"ui\label.jpg").scaled(label_T.size(), Qt.KeepAspectRatio, Qt.SmoothTransformation))

        button_close = QPushButton(self)
        button_close.setStyleSheet("QPushButton {border: none;}")
        button_close.setIcon(QIcon(r"ui\close.png"))
        button_close.resize(50, 50)
        button_close.move(1410, 0)
        button_close.clicked.connect(self.close)

        button_min = QPushButton(self)
        button_min.setStyleSheet("QPushButton {border: none;}")
        button_min.setIcon(QIcon(r"ui\min.png"))
        button_min.resize(50, 50)
        button_min.move(1360, 0)
        button_min.clicked.connect(self.showMinimized)
# ————————————————————————————————————————————————————————————
        tensorboradshow.setObjectName("tensorboradshow")
        tensorboradshow.resize(1460, 800)
        tensorboradshow.setMinimumSize(QtCore.QSize(1460, 800))
        tensorboradshow.setMaximumSize(QtCore.QSize(1460, 800))

        self.t_url_state_textedit = QtWidgets.QTextEdit(tensorboradshow)
        self.t_url_state_textedit.setGeometry(QtCore.QRect(1240, 70, 200, 700))
        self.t_url_state_textedit.setObjectName("t_url_state_textedit")
# ————————————————————————————————————————————————————————————
        ## 创建web窗体
        '''
        在QT Designer里面，没有WebEngine窗体，只能在程序中创建，先将其他的部分放好。
        '''
        self.qwebengine = QtWebEngineWidgets.QWebEngineView(tensorboradshow)
        self.qwebengine.setGeometry(20, 70, 1200, 700)
        self.retranslateUi(tensorboradshow)
        QtCore.QMetaObject.connectSlotsByName(tensorboradshow)

    def retranslateUi(self, tensorboradshow):
        font = QtGui.QFont()
        font.setFamily("Adobe 黑体 Std R")
        font.setPointSize(10)
        font.setBold(True)
        font.setStyleStrategy(QtGui.QFont.PreferAntialias)

        _translate = QtCore.QCoreApplication.translate
        tensorboradshow.setWindowTitle(_translate("tensorborad", "tensorborad"))

        url = 'http://localhost:6006/#timeseries'
        self.qwebengine.load(QtCore.QUrl(url))  # 打开网页
        self.get_error_mode(url)
        self.t_url_state_textedit.setFont(font)
        self.t_url_state_textedit.setReadOnly(True)

    def setCenter(self):
        screen = QDesktopWidget().screenGeometry()
        size = self.geometry()
        self.move(int((screen.width() - size.width()) / 2), int((screen.height() - size.height()) / 2))

    ## 将获取网站状态码以及输出异常域名的功能写成函数，调用的时候只需要将文件路径放进参数即可
    def get_error_mode(self, url):
        try:
            start = time.perf_counter()
            ## 配置超时时间
            file = urllib.request.urlopen(url, timeout=100)
            ## 获取访问状态
            elapsed = (time.perf_counter() - start)
            self.t_url_state_textedit.setText(
                str("%s可正常访问" % url) + '\n' + str("状态码：%s" % file.getcode() + '\n' +
                                                  str("耗时：%s" % round(elapsed, 4))))
            print("%s可正常访问" % url)
            print("状态码：%s" % file.getcode())
            print("耗时：%s" % round(elapsed, 4))

        # 异常域名会进入except，可以得到出错URLError
        except urllib.error.URLError as e:
            print("%s异常" % url)
            if hasattr(e, "code"):
                print("错误状态码： %s" % e.code)
                self.t_url_state_textedit.setText(str("%s异常" % url) + '\n' + str("错误状态码： %s" % e.code))
            if hasattr(e, "reason"):
                print("出错原因:%s" % e.reason)
                self.t_url_state_textedit.setText(str("%s异常" % url) + '\n' + str("出错原因:%s" % e.reason))